import CollectionUtil from '@/framework/infra/collection/CollectionUtil'
import { routerNameManager } from '@/framework/infra/router/routerNameManager'

export default class RouterUtil {

  static _routes = []

  static loadView(path) {
    return resolve => require([`@/${path}.vue`], resolve)
  }

  static getByName(routes, name) {
    for (const route of routes) {
      if (route.name === name) {
        return route
      }
      if (!CollectionUtil.isEmpty(route.children)) {
        const result = this.getByName(route.children, name)
        if (result) {
          return result
        }
      }
    }
    return null
  }

  static getByFullPath(routes, name) {
    for (const route of routes) {
      if (route._fullPath === name) {
        return route
      }
      if (!CollectionUtil.isEmpty(route.children)) {
        const result = this.getByFullPath(route.children, name)
        if (result) {
          return result
        }
      }
    }
    return null
  }

  static getButtonsByName(routes, name, groupId = 0) {
    let result = this.getByName(routes, name)
    if (result) {
      result = result.buttons || []
      if (groupId >= 0) {
        return result.filter(el => el.groupId === groupId)
      }
      return result
    }
    return null
  }

  static getButtonsByFullPath(routes, fullPath, groupId = 0) {
    let result = this.getByFullPath(routes, fullPath)
    if (result) {
      result = result.buttons || []
      if (groupId >= 0) {
        return result.filter(el => el.groupId === groupId)
      }
      return result
    }
    return null
  }

  // 路由预处理
  static prepareHandleRoute(routes, parentPath = '') {
    if (routes.__handled) {
      return routes
    }
    routes.__handled = true
    for (const route of routes) {
      if (route.name) {
        route.name = routerNameManager.addName(route.name)
      }
      route._fullPath = parentPath + (route.path.startsWith('/') ? '' : '/') + route.path
      if (route.buttons) {
        route.buttons.forEach(btn => {
          if (btn.name) {
            btn.name = routerNameManager.addName(btn.name)
          }
          if (!btn.funcType) {
            const handler = btn.handler || btn.name
            const parts = handler.split(':')
            btn.funcType = parts[parts.length - 1].replace(/[-_]+(\w)/g, (a, a1) => a1.toUpperCase())
          }
        })
      }
      if (!CollectionUtil.isEmpty(route.children)) {
        this.prepareHandleRoute(route.children, route._fullPath)
      }
    }
    return routes
  }

  static register(routes) {
    this._routes = this._routes.concat(routes)
  }

  static getRoutes() {
    return this.prepareHandleRoute(this._routes)
  }
}
